package com.tensquare.article.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.tensquare.article.pojo.Article;
import com.tensquare.article.service.ArticleService;
import com.tensquare.entity.PageResult;
import com.tensquare.entity.Result;
import com.tensquare.entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @RequestMapping(method = RequestMethod.PUT)
    public Result update(@RequestBody Article article){
        int count = articleService.update(article);
        if(count>0){
            return new Result(true,StatusCode.OK,"修改成功");
        }else{
            return new Result(false,StatusCode.ERROR,"修改失败，无法找到对应的ID");
        }
    }


    /**
     * 根据ID删除
     * @param id
     * @return
     */
    @RequestMapping(value="/{id}",method = RequestMethod.DELETE)
    public Result deleteById(@PathVariable("id") String id){
        articleService.deleteById(id);
        return new Result(true,StatusCode.OK,"删除成功");
    }

    /**
     * 新增
     * @param article
     * @return
     */
    @RequestMapping(method = RequestMethod.POST)
    public Result save(@RequestBody Article article){
        articleService.save(article);
        return new Result(true,StatusCode.OK,"新增成功");
    }

    /**
     * 查询所有
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public Result findAll(){
        List<Article> articles = articleService.findAll();
        return new Result(true, StatusCode.OK,"查询成功",articles);
    }

    /**
     * 按条件分页查询
     * pageNum 页码
     * pageSize 页面大小
     * map 查询条件
     */

    @RequestMapping(value = "/search/{pageNum}/{pageSize}",method = RequestMethod.POST)
    public Result findByPage(@PathVariable("pageNum") Integer pageNum,
                             @PathVariable("pageSize") Integer pageSize,
                             @RequestBody Map<String,Object> map
    ){
        Page<Article> pageData = articleService.findByPage(pageNum,pageSize,map);
        PageResult<Article> pageResult = new PageResult(
                pageData.getTotal(),pageData.getRecords()
        );
        return new Result(true,StatusCode.OK,"查询成功",pageResult);
    }
}
